import { HttpClient } from '@angular/common/http';
import { Component, DestroyRef, inject } from '@angular/core';
import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms';

@Component({
  selector: 'app-login',
  imports: [FormsModule, ReactiveFormsModule],
  templateUrl: './login.component.html',
  styleUrl: './login.component.css'
})
export class LoginComponent {
  loginForm = new FormGroup({
    userName: new FormControl(),
    password: new FormControl()
  })
  private httpClient = inject(HttpClient);
  private baseURL = "http://localhost:5286/api";
  private destroyRef = inject(DestroyRef);
  onSubmit() {
    var user = { userName: this.loginForm.controls.userName.value, password: this.loginForm.controls.password.value };
    const subscription = this.httpClient.post<{ access_token: string, expiresAt: string }>(this.baseURL + "/auth", user).subscribe({
      next: (jwt) => { console.log(jwt.access_token); localStorage.setItem("Authorization", 'Bearer ' + jwt.access_token); }
    });
    this.destroyRef.onDestroy(() => { subscription.unsubscribe() });
  }
}
